<template>
  <div class="main-box">
    <TreeFilter label="name" title="配置类型(单选)" :data="treeFilterData" @change="changeTreeFilter" />
    <div class="table-box">
      <div class="card content-box">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="220px" v-if="selected">
          <el-row :gutter="20">
            <el-col :span="24" v-for="(item, itemIndex) in selected.fields" :key="item">
              <template v-if="item.is_unique >= 1">
                <el-form-item :label="item.label" :prop="item.field">
                  <template v-if="item.input == 'input'">
                    <el-input v-model="ruleForm[item.field]" :placeholder="item.desc" />
                  </template>

                  <template v-if="item.input == 'radio'">
                    <el-radio-group v-model="ruleForm[item.field]">
                      <el-radio
                        :label="source.value"
                        size="large"
                        border
                        v-for="(source, index) in JSON.parse(item.source)"
                        :key="index"
                      >
                        {{ source.label }}
                      </el-radio>
                    </el-radio-group>
                  </template>

                  <template v-if="item.input == 'select'">
                    <el-select v-model="ruleForm[item.field]" clearable placeholder="Select">
                      <el-option
                        v-for="item in JSON.parse(item.source)"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>

                  <template v-if="item.input == 'switch'">
                    <el-switch
                      v-model="ruleForm[item.field]"
                      class="ml-2"
                      style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                    />
                  </template>

                  <template v-if="item.input == 'timePicker'">
                    <el-time-picker v-model="ruleForm[item.field]" placeholder="Arbitrary time" />
                  </template>

                  <template v-if="item.input == 'timeSelect'">
                    <el-time-select v-model="ruleForm[item.field]" placeholder="Select time" />
                  </template>

                  <template v-if="item.input == 'datePicker'">
                    <el-date-picker v-model="ruleForm[item.field]" type="date" placeholder="Pick a day" size="large" />
                  </template>

                  <template v-if="item.input == 'dateTimePicker'">
                    <el-date-picker v-model="ruleForm[item.field]" type="datetime" placeholder="Select date and time" />
                  </template>

                  <template v-if="item.input == 'checkbox'">
                    <el-checkbox-group v-model="ruleForm[item.field]">
                      <el-checkbox v-for="item in JSON.parse(item.source)" :label="item.value" :key="item">
                        {{ item.label }}</el-checkbox
                      >
                    </el-checkbox-group>
                  </template>

                  <template v-if="item.input == 'resources'">
                    <Resources v-model="ruleForm[item.field]" />
                  </template>
                </el-form-item>
              </template>

              <template v-else>
                <el-form-item :label="item.label" :prop="item.field">
                  <template v-if="item.input == 'input'">
                    <el-input v-model="ruleForm[item.field][itemIndex]" :placeholder="item.desc" />
                  </template>

                  <template v-if="item.input == 'radio'">
                    <el-radio-group v-model="ruleForm[item.field][itemIndex]">
                      <el-radio
                        :label="source.value"
                        size="large"
                        border
                        v-for="(source, index) in JSON.parse(item.source)"
                        :key="index"
                      >
                        {{ source.label }}
                      </el-radio>
                    </el-radio-group>
                  </template>

                  <template v-if="item.input == 'select'">
                    <el-select v-model="ruleForm[item.field][itemIndex]" clearable placeholder="Select">
                      <el-option
                        v-for="item in JSON.parse(item.source)"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>

                  <template v-if="item.input == 'switch'">
                    <el-switch
                      v-model="ruleForm[item.field][itemIndex]"
                      class="ml-2"
                      style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                    />
                  </template>

                  <template v-if="item.input == 'timePicker'">
                    <el-time-picker v-model="ruleForm[item.field][itemIndex]" placeholder="Arbitrary time" />
                  </template>

                  <template v-if="item.input == 'timeSelect'">
                    <el-time-select v-model="ruleForm[item.field][itemIndex]" placeholder="Select time" />
                  </template>

                  <template v-if="item.input == 'datePicker'">
                    <el-date-picker v-model="ruleForm[item.field][itemIndex]" type="date" placeholder="Pick a day" size="large" />
                  </template>

                  <template v-if="item.input == 'dateTimePicker'">
                    <el-date-picker
                      v-model="ruleForm[item.field][itemIndex]"
                      type="datetime"
                      placeholder="Select date and time"
                    />
                  </template>

                  <template v-if="item.input == 'checkbox'">
                    <el-checkbox-group v-model="ruleForm[item.field][itemIndex]">
                      <el-checkbox
                        v-for="item in JSON.parse(item.source)"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-checkbox-group>
                  </template>

                  <template v-if="item.input == 'resources'">
                    <Resources v-model="ruleForm[item.field][itemIndex]" />
                  </template>
                </el-form-item>
              </template>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8"></el-col>
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
              <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx">
import { onMounted, ref } from "vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { settingList, settingCreate, settingUpdate } from "@/api/modules/common";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import Resources from "@/components/Resources/index.vue";
// import { useI18n } from "vue-i18n";

// const { t } = useI18n();
onMounted(() => {
  getTreeFilter();
});

// 获取 treeFilter 数据
// 当 proTable 的 requestAuto 属性为 false，不会自动请求表格数据，等待 treeFilter 数据回来之后，更改 initParam.departmentId 的值，才会触发请求 proTable 数据
const treeFilterData = ref<any>([]);
const configList = {};
const getTreeFilter = async () => {
  const { data } = await settingList();
  console.log(data);
  treeFilterData.value = data;
  data.forEach(item => {
    configList[item.id] = item;
    item.children.forEach(child => {
      configList[child.id] = child;
    });
  });
};

const rules = ref({});
const ruleForm = ref({});
const selected = ref(null);
const validator = {
  max: (rule, value, callback) => {
    const num = parseFloat(value);
    if (isNaN(num)) {
      callback(new Error("请输入数字"));
    } else if (num > rule.max) {
      callback(new Error(rule.message));
    } else {
      callback();
    }
  },
  min: (rule, value, callback) => {
    const num = parseFloat(value);
    if (isNaN(num)) {
      callback(new Error("请输入数字"));
    } else if (num < rule.min) {
      callback(new Error(rule.message));
    } else {
      callback();
    }
  }
};

// 树形筛选切换
const changeTreeFilter = (val: string) => {
  selected.value = val ? configList[val] : null;
  ruleForm.value = {};
  rules.value = {};
  if (selected.value) {
    ruleForm.value.config_id = selected.value.id;
    ruleForm.value.id = selected.value.setting_id > 0 ? selected.value.setting_id : 0;
    selected.value.fields.forEach(child => {
      const item = JSON.parse(JSON.stringify(child));
      item.rules = JSON.parse(item.rules);
      if (item.is_unique) {
        ruleForm.value[item.field] = item.value;
      } else {
        if (typeof ruleForm.value[item.field] == "undefined") {
          ruleForm.value[item.field] = [];
        }

        ruleForm.value[item.field].push(item.value);
      }

      item.rules.forEach(rule => {
        rule.trigger = "blur";
        Object.keys(validator).forEach(key => {
          if (rule[key] !== undefined) {
            rule.validator = validator[key];
          }
        });
      });

      rules.value[item.field] = item.rules;
    });
  }
};

const ruleFormRef = ref<FormInstance>();
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      const action = ruleForm.value.id > 0 ? settingUpdate : settingCreate;
      const result = JSON.parse(JSON.stringify(ruleForm.value));
      const formData = {};
      if (result.id > 0) {
        formData.id = result.id;
      } else {
        formData.config_id = result.config_id;
      }

      delete result["id"];
      delete result["config_id"];
      formData.result = result;
      action(formData).then(response => {
        ElMessage.success(response.message);
      });
    }
  });
};
</script>
<style scoped lang="scss">
.el-form {
  width: 100%;
  .text-center {
    text-align: center;
  }
}
</style>
